/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.klikmee.sms.core.base.util;

import javax.servlet.ServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 *
 * @author makcro
 *
 */

/*
 * Used to Lookup Spring managed beans in java POJO classes
 * Spring WebApplicationContext is automaticaly initialized after deployment of application
 */
public class SpringBeansLookup {

    private static WebApplicationContext applicationContext;
    private static ServletContext servletContext;
    /*
     * called after app deployment by servlet container.
     *
     * @param servletContext current web app servlet context used to initialize spring webapplication context
     */

    public static void init( ServletContext servletContext ) {
        applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext( servletContext );
        SpringBeansLookup.servletContext = servletContext;

    }

    /*
     * Retreives spring managed based on name configured in spring xml configuration files.
     * Example:
     * UserRoleDAO userRoleDAO = (UserRoleDAO) SpringBeansLookup.getBean( SpringBeansLookup.USER_ROLE_DAO);
     */
    public static Object getBean( String beanName ) {
        return applicationContext.getBean( beanName );
    }

    public static <T extends Object> T getBean( Class<T> beanClass ) {
        return applicationContext.getBean( beanClass );
    }

    public static ServletContext getServletContext() {
        return SpringBeansLookup.servletContext;
    }
}
